<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use Illuminate\Support\Facades\Hash;

class UserController extends CommonController
{
    //用户控制器

    //登录
    public function login(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();
            $res = User::where('tel', $data['tel'])->first();

            if (!$res) {
                return redirect('/login')->with('status', '貌似有问题');
            }

            if (Hash::check($data['password'], $res['password'])) {
                session(['user' => $res]);
                return redirect('/');
            } else {
                return redirect('/login')->with('status', '貌似有问题');
            }
        }
        return view('home.user.login');

    }

    //注册
    public function register(Request $request, User $user)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();
            $rules = '/^1[3-9]\d{9}$/';
            if (!preg_match($rules, $data['tel'])) {
                return redirect('/register')->with('status', '手机号码不对');
            }
            if ($data['password'] != $data['password2']) {
                return redirect('/register')->with('status', '密码不一致');
            }
            $user->tel = $data['tel'];
            $user->password = Hash::make($data['password']);
            $user->save();
            return redirect('/login');
        }
        return view('home.user.register');

    }


    //退出登录
    public function loginout(Request $request)
    {
        $request->session()->forget('user');
        return redirect('/');
    }

}
